<?php

namespace app\common\util\plug;

use app\common\util\base\BaseServer;
use app\common\util\FileUtil;

class PlugInstall extends BaseServer
{
    /**
     * 插件解压后缓存路径
     */
    protected $plugTempPath;

    /**
     * 插件配置信息
     */
    protected $plugInfo;

    /**
     * 插件路径
     */
    protected $plugPath;

    /**
     * 插件压缩包文件
     */
    protected $file;
    public function __construct($file = null)
    {
        if ($file != null) {
            $this->file = $file;
            $zipName = $file->getBasename();
            $hash = hash_file('md5',$zipName);
            $this->plugTempPath = app_path('plug').$hash.'/';
        }
    }

    public function __destruct()
    {
        if($this->file != null){
            FileUtil::delDirAndFile($this->plugTempPath);
        }
    }

    public function handle()
    {
        $res = [];
        foreach ($this->observer as $observer) {
            $res[] = $observer->handle($this);
        }
        return $res;
    }

    /**
     * @return mixed
     */
    public function getPlugInfo()
    {
        return $this->plugInfo;
    }

    /**
     * 获取加载的插件配置信息
     * @param mixed $plugInfo
     */
    public function setPlugInfo($plugInfo)
    {
        $this->plugInfo = $plugInfo;
        return $this;
    }

    /**
     * 获取插件临时文件
     * @return \think\file\UploadedFile|think\File
     */
    public function getFile()
    {
        return $this->file;
    }

    public function setPlugPath($path){
        $this->plugPath = $path;
        return $this;
    }

    public function getPlugPath(){
        return $this->plugPath;
    }
    /**
     * @param \think\file\UploadedFile|think\File $file
     */
    public function setFile($file)
    {
        $hash = hash_file('md5',$file->getPathname());
        $this->plugTempPath = app_path('plug').$hash.'/';
        $this->file = $file;
        return $this;
    }

    /**
     * 获取插件临时目录
     * @return string
     */
    public function getPlugTempPath(): string
    {
        return $this->plugTempPath;
    }

    /**
     * @param string $plugTempPath
     */
    public function setPlugTempPath(string $plugTempPath): void
    {
        $this->plugTempPath = $plugTempPath;
    }
}